﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Http;
using YlisChat.Models;

namespace YlisChat.Controllers
{
    // TODO: Authorize
    public class DownloadController : BaseController
    {
        // GET: api/Download
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        /// <summary>
        /// Download the attachment
        /// GET: api/Download/guid
        /// </summary>
        /// <param name="id">the guid of the attachment</param>
        /// <returns>The attachment contents</returns>
        public async Task<HttpResponseMessage> Get(string id)
        {
            if (String.IsNullOrWhiteSpace(id))
                return new HttpResponseMessage(HttpStatusCode.BadRequest);

            Attachments attachment = await(from att in db.Attachments
                                           where att.Id == id
                                           select att).FirstOrDefaultAsync();

            if (attachment == default(Attachments))
                return new HttpResponseMessage(HttpStatusCode.NotFound);


            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            try
            {
                FileStream stream = new FileStream(attachment.InternalName, FileMode.Open);
                result.Content = new StreamContent(stream);
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = attachment.OriginalName
                };
            }
            catch (Exception)
            {
                // Answer 404 Not Found if errors happen while opening the file
                return new HttpResponseMessage(HttpStatusCode.NotFound);
            }
            return result;
        }

    }
}
